<template>
  <div class="fixed top-24 left-4 bg-[#0a1a2f]/90 rounded-lg shadow-2xl border border-[#00eaff]/30 w-[280px] z-30 backdrop-blur-md overflow-hidden">
    <!-- 标题栏 -->
    <div class="px-4 py-3 border-b border-[#00eaff]/30 bg-[#0a1a2f]/60">
      <div class="flex items-center space-x-2">
        <i class="fas fa-layer-group text-[#00eaff] text-lg"></i>
        <h3 class="text-lg font-medium text-[#00eaff]">图层管理</h3>
      </div>
    </div>

    <!-- 图层列表 -->
    <div class="px-3 py-2 max-h-[calc(100vh-180px)] overflow-y-auto">
      <div v-if="layers.length > 0" class="space-y-1">
        <div v-for="layer in reversedLayers" :key="layer.id" 
             class="group flex items-center p-2.5 rounded-lg hover:bg-[#1e3a5c]/40 transition-all duration-200"
             :class="{'opacity-60': !isLayerInVisibleRange(layer)}"
             @click="toggleLayer(layer)">
          <!-- 复选框容器 -->
          <div class="relative flex items-center justify-center w-5 h-5">
            <input
              type="checkbox"
              :id="layer.id"
              v-model="layer.visible"
              class="layer-checkbox absolute opacity-0 w-5 h-5 cursor-pointer"
              @click.stop
              @change="handleVisibilityChange(layer)"
            />
            <div class="checkbox-custom w-5 h-5 rounded border-2 border-[#00eaff]/40 transition-all duration-200 flex items-center justify-center">
              <i class="fas fa-check text-xs text-[#00eaff] opacity-0 transform scale-0 transition-all duration-200"></i>
            </div>
          </div>

          <!-- 图层图标和名称 -->
          <div class="flex items-center ml-3 flex-1">
            <i :class="getLayerIcon(layer.id)" class="text-[#00eaff]/80 mr-2 w-5 text-center"></i>
            <span class="text-sm font-medium text-gray-100 cursor-pointer select-none group-hover:text-[#00eaff] transition-colors duration-200">
              {{ layer.name }}
            </span>
            <!-- 可见层级指示器 -->
            <div class="ml-auto flex items-center space-x-1">
              <span v-if="!isLayerInVisibleRange(layer)" class="text-xs text-amber-400/80">
                <i class="fas fa-eye-slash mr-1"></i>{{ getVisibleRangeText(layer) }}
              </span>
              <span v-else class="text-xs text-emerald-400/80">
                <i class="fas fa-eye mr-1"></i>
              </span>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="text-sm text-gray-400/80 italic text-center py-4">暂无可管理图层</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'

const props = defineProps({
  map: {
    type: Object,
    required: true
  }
})

const layers = ref([])

// 计算反转后的图层顺序
const reversedLayers = computed(() => {
  return [...layers.value].reverse()
})

// 获取图层对应的图标
const getLayerIcon = (layerId) => {
  const icons = {
    'arcgis-satellite': 'fas fa-satellite',
    'buildings': 'fas fa-building',
    'landuse': 'fas fa-tree',
    'natural': 'fas fa-leaf',
    'places': 'fas fa-map-marker-alt',
    'points': 'fas fa-dot-circle',
    'railways': 'fas fa-train',
    'roads': 'fas fa-road',
    'waterways': 'fas fa-water'
  }
  return icons[layerId] || 'fas fa-layer-group'
}

// 检查图层是否在可见缩放范围内
const isLayerInVisibleRange = (layer) => {
  if (!props.map || !layer) return false
  const zoom = props.map.getZoom()
  return zoom >= layer.minzoom && zoom <= layer.maxzoom
}

// 获取图层可见范围文本
const getVisibleRangeText = (layer) => {
  if (!layer) return ''
  return `缩放 ${layer.minzoom}-${layer.maxzoom}`
}

const updateLayersFromStyle = () => {
  if (!props.map || !props.map.getStyle) return
  try {
    const style = props.map.getStyle()
    const newLayers = []

    if (style && style.layers && Array.isArray(style.layers)) {
      style.layers.forEach(layer => {
        if (["raster", "fill", "line", "symbol", "circle"].includes(layer.type)) {
          const visibility = props.map.getLayoutProperty(layer.id, 'visibility')
          newLayers.push({
            id: layer.id,
            name: layer.id.replace(/-/g, ' ').replace(/_/g, ' '),
            visible: !visibility || visibility === 'visible',
            minzoom: layer.minzoom || 0,
            maxzoom: layer.maxzoom || 22
          })
        }
      })
    }
    layers.value = newLayers
  } catch (error) {
    console.error('Error updating layers:', error)
    layers.value = []
  }
}

const handleVisibilityChange = (layer) => {
  if (!props.map) return
  try {
    const visibility = layer.visible ? 'visible' : 'none'
    props.map.setLayoutProperty(layer.id, 'visibility', visibility)
  } catch (error) {
    console.error('Error handling visibility change:', error)
  }
}

const toggleLayer = (layer) => {
  if (!props.map) return
  try {
    layer.visible = !layer.visible
    handleVisibilityChange(layer)
  } catch (error) {
    console.error('Error toggling layer:', error)
  }
}

onMounted(() => {
  if (props.map) {
    if (props.map.isStyleLoaded && props.map.isStyleLoaded()) {
      updateLayersFromStyle()
    } else {
      props.map.on('styledata', updateLayersFromStyle)
      props.map.on('load', updateLayersFromStyle)
    }

    // 监听地图缩放事件以更新图层状态
    props.map.on('zoom', () => {
      layers.value.forEach(layer => {
        if (isLayerInVisibleRange(layer) && layer.visible) {
          props.map.setLayoutProperty(layer.id, 'visibility', 'visible')
        }
      })
    })
  }
})

// 监听地图样式变化
watch(() => props.map && props.map.getStyle && props.map.getStyle(), updateLayersFromStyle, { deep: true })
</script>

<style scoped>
/* 自定义复选框样式 */
.layer-checkbox:checked + .checkbox-custom {
  @apply bg-[#1e3a5c]/50 border-[#00eaff];
}

.layer-checkbox:checked + .checkbox-custom i {
  @apply opacity-100 scale-100;
}

.layer-checkbox:hover + .checkbox-custom {
  @apply border-[#00eaff];
}

/* 滚动条样式 */
.overflow-y-auto::-webkit-scrollbar {
  width: 6px;
}

.overflow-y-auto::-webkit-scrollbar-track {
  background: rgba(0, 234, 255, 0.05);
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
  background: rgba(0, 234, 255, 0.2);
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 234, 255, 0.3);
}

/* 容器发光效果 */
.checkbox-custom {
  box-shadow: 0 0 0 0 rgba(0, 234, 255, 0);
  transition: all 0.3s ease;
}

/* 悬停时的发光效果 */
.group:hover .checkbox-custom {
  box-shadow: 0 0 12px rgba(0, 234, 255, 0.2);
}

/* 选中状态的发光效果 */
.layer-checkbox:checked + .checkbox-custom {
  box-shadow: 0 0 12px rgba(0, 234, 255, 0.3);
}
</style> 